<?php

namespace app\admin\controller;

use controller\BasicAdmin;
use service\DataService;
use service\ToolsService;
use think\Db;
use think\exception\HttpResponseException;
use think\facade\Cache;

/**
 * 分类管理
 */
class InfoCate extends BasicAdmin
{

    /**
     * 定义当前操作表名
     * @var string
     */
    public $info_cate = 'tp_vote_cate';

    /**
     * 分类列表
     * @return array|string
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function lists()
    {
        $this->title = '分类';
        $db = Db::name($this->info_cate);
        if ($this->request->isPost()) {
            Cache::store('redis')->handler()->del('new_cate:list');
        }
        return parent::_list($db->order('cate_id asc'), 'cate_id', false);
    }

    /**
     * 列表数据处理
     * @param array $data
     */
    protected function _data_filter(&$data)
    {
        foreach ($data as &$vo) {
            $vo['ids'] = join(',', ToolsService::getArrSubIds($data, $vo['cate_id'], 'cate_id'));
        }
        $data = ToolsService::arr2table($data, 'cate_id');;
    }

    /**
     * 添加
     * @return array|string
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function add()
    {
        Cache::store('redis')->handler()->del('new_cate:list');
        return $this->_form($this->info_cate, 'form');
    }

    /**
     * 编辑
     * @return array|string
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function edit()
    {
        if (!$this->request->isPost()) {
            $cate_id = $this->request->get('id');
            $cate = Db::name($this->info_cate)->where(['cate_id' => $cate_id])->find();
            $this->_form_filter($cate);
            empty($cate) && $this->error('需要编辑的分类不存在！');
            return $this->fetch('form', ['vo' => $cate, 'title' => '编辑分类']);
        }
        try {
            $cate_id = $this->request->post('id');
            $data = $this->request->post();
            $cate = Db::name($this->info_cate)->where(['cate_id' => $cate_id])->find();
            empty($cate) && $this->error('编辑分类失败，请稍候再试！');

            Db::transaction(function () use ($data, $cate_id, $cate) {
                $where = ['cate_id' => $cate_id];
                Db::name($this->info_cate)->where($where)->update($data);
                Cache::store('redis')->handler()->del('new_cate:list');
            });

        } catch (HttpResponseException $exception) {
            return $exception->getResponse();
        } catch (\Exception $e) {
            $this->error('编辑分类失败，请稍候再试！' . $e->getMessage());
        }
        $this->success('编辑分类成功！', "");
    }

    /**
     * 表单数据前缀方法
     * @param array $vo
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    protected function _form_filter(&$vo)
    {
        if ($this->request->isGet()) {
            // 读取上级分类
            $where = ['pid' => '0',];
            $_cates = (array)Db::name($this->info_cate)->where($where)->order('sort desc,cate_id asc')->select();
            array_unshift($_cates, ['cate_id' => 0, 'pid' => -1, 'name' => '--- 顶级分类 ---']);
            $cates = ToolsService::arr2table($_cates, 'cate_id');
            foreach ($cates as $key => &$cate) {
                if (isset($vo['pid'])) {
                    $path = "-{$vo['pid']}-{$vo['cate_id']}";
                    if ($vo['pid'] !== '' && (stripos("{$cate['path']}-", "{$path}-") !== false || $cate['path'] === $path)) {
                        unset($cates[$key]);
                    }
                }
            }
            $this->assign('cates', $cates);
        }
    }

    /**
     * 删除分类
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function del()
    {
        Cache::store('redis')->handler()->del('new_cate:list');
        if (DataService::update($this->info_cate)) {
            $this->success("分类删除成功！", '');
        }
        $this->error("分类删除失败，请稍候再试！");
    }

    /**
     * 分类禁用
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function forbid()
    {
        Cache::store('redis')->handler()->del('new_cate:list');
        if (DataService::update($this->info_cate)) {
            $this->success("分类禁用成功！", '');
        }
        $this->error("分类禁用失败，请稍候再试！");
    }

    /**
     * 分类禁用
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function resume()
    {
        Cache::store('redis')->handler()->del('new_cate:list');
        if (DataService::update($this->info_cate)) {
            $this->success("分类启用成功！", '');
        }
        $this->error("分类启用失败，请稍候再试！");
    }

}
